﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MstscHelperApp
{
    /// <summary>
    /// 远程桌面管理器主窗体
    /// </summary>
    public partial class Form1 : Form
    {

        // 存储远程桌面信息的JSON文件路径
        string mstscjsonPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "mstscdata.json");
        // 远程桌面信息列表
        List<MsctcInfo> mstscInfos = new List<MsctcInfo>();

        /// <summary>
        /// 构造函数，初始化窗体
        /// </summary>
        public Form1()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 窗体加载事件，初始化控件和数据
        /// </summary>
        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
                shuaxin(); // 刷新数据
                dataGridView1.CellClick += DataGridView1_CellClick;
                if (!IsAdministrator())
                {
                    this.Text = "远程桌面管理器（非管理员模式）";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("加载出错了：" + ex.Message);
            }
        }

        /// <summary>
        /// 判断当前进程是否以管理员身份运行
        /// </summary>
        public static bool IsAdministrator()
        {
            WindowsIdentity identity = WindowsIdentity.GetCurrent();
            WindowsPrincipal principal = new WindowsPrincipal(identity);
            return principal.IsInRole(WindowsBuiltInRole.Administrator);
        }

        /// <summary>
        /// DataGridView单元格点击事件，处理“启动”按钮点击
        /// </summary>
        private void DataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (e.ColumnIndex == dataGridView1.Columns["操作"].Index && e.RowIndex >= 0)
                {
                    var ip = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
                    if (mstscInfos.Count == 0)
                    {
                        shuaxin();
                    }
                    var info = mstscInfos.FirstOrDefault(x => x.IP == ip);
                    if (info != null)
                    {
                        var reqpath = MstscStartHelpr.StartMstsc(info);
                        Thread.Sleep(1000); // 等待1秒钟，确保RDP文件生成
                        if (File.Exists(reqpath))
                        {
                            File.Delete(reqpath);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("启动出错了：" + ex.Message);
            }
        }

        /// <summary>
        /// 刷新DataGridView和分组下拉框的数据
        /// </summary>
        private void shuaxin()
        {
            try
            {
                if (File.Exists(mstscjsonPath))
                {
                    var jsondata = File.ReadAllText(mstscjsonPath);
                    if (!string.IsNullOrEmpty(jsondata))
                    {
                        mstscInfos = JsonHelper.JsonToT<List<MsctcInfo>>(jsondata);
                        mstscInfos = mstscInfos.OrderBy(m => m.Group).ThenBy(m => m.IP).ToList();
                        dataGridView1.Rows.Clear();
                        foreach (var item in mstscInfos)
                        {
                            dataGridView1.Rows.Add(false, item.Group, item.IP, item.Desc, "启动");
                        }
                        var groups = mstscInfos.Select(m => m.Group).Distinct().ToList();
                        comboBox1.Items.Clear();
                        comboBox1.Items.Add("全部分组");
                        foreach (var group in groups)
                        {
                            comboBox1.Items.Add(group);
                        }
                    }
                }
                else
                {
                    dataGridView1.Rows.Clear();
                    comboBox1.Items.Clear();
                    comboBox1.Items.Add("全部分组");
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        /// <summary>
        /// 新增按钮点击事件，弹出新增窗口
        /// </summary>
        private void xzbtn_Click(object sender, EventArgs e)
        {
            try
            {
                Form2 form2 = new Form2();
                form2.StartPosition = FormStartPosition.CenterParent;
                var result = form2.ShowDialog(this);
                if (result == DialogResult.OK)
                {
                    shuaxin();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("新增出错了：" + ex.Message);
            }
        }

        /// <summary>
        /// 查询按钮点击事件，根据条件过滤显示服务器
        /// </summary>
        private void cxbtn_Click(object sender, EventArgs e)
        {
            try
            {
                if (File.Exists(mstscjsonPath))
                {
                    var jsondata = File.ReadAllText(mstscjsonPath);
                    if (!string.IsNullOrEmpty(jsondata))
                    {
                        mstscInfos = JsonHelper.JsonToT<List<MsctcInfo>>(jsondata);
                        if (!string.IsNullOrEmpty(comboBox1.Text) && comboBox1.Text != "全部分组")
                        {
                            mstscInfos = mstscInfos.Where(m => m.Group == comboBox1.Text).ToList();
                        }
                        if (!string.IsNullOrWhiteSpace(textBox1.Text))
                        {
                            mstscInfos = mstscInfos.Where(m => m.IP.Contains(textBox1.Text)).ToList();
                        }
                        if (!string.IsNullOrWhiteSpace(textBox2.Text))
                        {
                            mstscInfos = mstscInfos.Where(m => m.Desc.Contains(textBox2.Text)).ToList();
                        }
                        dataGridView1.Rows.Clear();
                        mstscInfos = mstscInfos.OrderBy(m => m.Group).ThenBy(m => m.IP).ToList();
                        foreach (var item in mstscInfos)
                        {
                            dataGridView1.Rows.Add(false, item.Group, item.IP, item.Desc, "启动");
                        }
                    }
                }
                else
                {
                    dataGridView1.Rows.Clear();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("查询出错了：" + ex.Message);
            }
        }

        /// <summary>
        /// 删除按钮点击事件，删除选中的服务器
        /// </summary>
        private void scbtn_Click(object sender, EventArgs e)
        {
            try
            {
                if (dataGridView1.Rows.Count == 0)
                {
                    MessageBox.Show("没有服务器可以删除");
                    return;
                }
                List<string> selectedIPs = new List<string>();
                foreach (DataGridViewRow item in dataGridView1.Rows)
                {
                    if (item.Cells["选择"].Value != null && (bool)item.Cells["选择"].Value)
                    {
                        selectedIPs.Add(item.Cells["地址"].Value.ToString());
                    }
                }
                if (selectedIPs.Count == 0)
                {
                    MessageBox.Show("没有选中任何服务器");
                    return;
                }
                if (selectedIPs.Count > 0)
                {
                    var result = MessageBox.Show("确定要删除吗？", "删除提示", MessageBoxButtons.OKCancel);
                    if (result == DialogResult.OK)
                    {
                        initMstscInfos();
                        var info = mstscInfos.Where(x => selectedIPs.Contains(x.IP)).ToList();
                        foreach (var item in info)
                        {
                            mstscInfos.Remove(item);
                        }
                        deletejsonAndAdd();
                        shuaxin();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("删除出错了：" + ex.Message);
            }
        }

        /// <summary>
        /// 重新加载mstscInfos数据
        /// </summary>
        private void initMstscInfos()
        {
            if (File.Exists(mstscjsonPath))
            {
                var jsondata = File.ReadAllText(mstscjsonPath);
                if (!string.IsNullOrEmpty(jsondata))
                {
                    mstscInfos = JsonHelper.JsonToT<List<MsctcInfo>>(jsondata);
                }
            }
        }

        /// <summary>
        /// 删除原有JSON并写入新数据
        /// </summary>
        private void deletejsonAndAdd()
        {
            try
            {
                if (File.Exists(mstscjsonPath))
                {
                    File.Delete(mstscjsonPath);
                }
                if (mstscInfos != null && mstscInfos.Any())
                {
                    File.WriteAllText(mstscjsonPath, JsonHelper.TtoJson(mstscInfos), Encoding.UTF8);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        /// <summary>
        /// 刷新按钮点击事件
        /// </summary>
        private void sxbtn_Click(object sender, EventArgs e)
        {
            try
            {
                shuaxin();
            }
            catch (Exception ex)
            {
                MessageBox.Show("刷新出错了。" + ex.Message);
            }
        }

        /// <summary>
        /// 修改按钮点击事件，弹出修改窗口
        /// </summary>
        private void xgbtn_Click(object sender, EventArgs e)
        {
            try
            {
                if (dataGridView1.Rows.Count == 0)
                {
                    MessageBox.Show("没有服务器可以修改");
                    return;
                }
                List<string> selectedIPs = new List<string>();
                foreach (DataGridViewRow item in dataGridView1.Rows)
                {
                    if (item.Cells["选择"].Value != null && (bool)item.Cells["选择"].Value)
                    {
                        selectedIPs.Add(item.Cells["地址"].Value.ToString());
                    }
                }
                if (selectedIPs.Count == 0)
                {
                    MessageBox.Show("没有选中任何服务器");
                    return;
                }
                if (selectedIPs.Count > 1)
                {
                    MessageBox.Show("无法一次修改多条");
                    return;
                }
                Form3 form3 = new Form3();
                form3.StartPosition = FormStartPosition.CenterParent;
                form3.IP = selectedIPs.FirstOrDefault(); // 设置要修改的IP地址
                var result = form3.ShowDialog();
                if (result == DialogResult.OK)
                {
                    shuaxin();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("修改出错了。" + ex.Message);
            }
        }

        /// <summary>
        /// 批量启动按钮点击事件
        /// </summary>
        private void plqdbtn_Click(object sender, EventArgs e)
        {
            try
            {
                if (dataGridView1.Rows.Count == 0)
                {
                    MessageBox.Show("没有服务器可以启动");
                    return;
                }
                List<string> selectedIPs = new List<string>();
                foreach (DataGridViewRow item in dataGridView1.Rows)
                {
                    if (item.Cells["选择"].Value != null && (bool)item.Cells["选择"].Value)
                    {
                        selectedIPs.Add(item.Cells["地址"].Value.ToString());
                    }
                }
                if (selectedIPs.Count == 0)
                {
                    MessageBox.Show("没有选中任何服务器");
                    return;
                }
                foreach (var item in selectedIPs)
                {
                    var info = mstscInfos.FirstOrDefault(x => x.IP == item);
                    if (info != null)
                    {
                        Task.Run(() =>
                        {
                            var reqpath = MstscStartHelpr.StartMstsc(info);
                            Thread.Sleep(1000); // 等待1秒钟，确保RDP文件生成
                            if (File.Exists(reqpath))
                            {
                                File.Delete(reqpath);
                            }
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("批量启动出错了。" + ex.Message);
            }
        }

        /// <summary>
        /// 导出按钮点击事件，导出服务器信息到json或txt
        /// </summary>
        private void dcbtn_Click(object sender, EventArgs e)
        {
            try
            {
                if (dataGridView1.Rows.Count == 0)
                {
                    MessageBox.Show("没有服务器可以导出");
                    return;
                }
                List<MsctcInfo> dcinfos = new List<MsctcInfo>();
                foreach (DataGridViewRow item in dataGridView1.Rows)
                {
                    var ip = item.Cells["地址"].Value.ToString();
                    dcinfos.Add(mstscInfos.FirstOrDefault(x => x.IP == ip));
                }
                var dlresult = MessageBox.Show("是否需要导出Json文件？选择否则导出txt文件。", "提示", MessageBoxButtons.YesNo);
                if (dlresult == DialogResult.Yes)
                {
                    string servicesdataPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "servicesdata.json");
                    if (File.Exists(servicesdataPath))
                    {
                        File.Delete(servicesdataPath);
                    }
                    if (dcinfos != null && dcinfos.Any())
                    {
                        File.WriteAllText(servicesdataPath, JsonHelper.TtoJson(dcinfos), Encoding.UTF8);
                    }
                    var yesorno = MessageBox.Show($"导出成功，文件路径：{servicesdataPath}。是否需要自动复制？", "提示", MessageBoxButtons.YesNo);
                    if (yesorno == DialogResult.Yes)
                    {
                        StringCollection strings = new StringCollection();
                        strings.Add(servicesdataPath);
                        Clipboard.SetFileDropList(strings);
                    }
                }
                else
                {
                    string servicesdataPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "servicesdata.txt");
                    if (File.Exists(servicesdataPath))
                    {
                        File.Delete(servicesdataPath);
                    }
                    foreach (var info in dcinfos)
                    {
                        File.AppendAllText(servicesdataPath, "---------------------------------------------------------------\r\n");
                        if (info != null)
                        {
                            File.AppendAllText(servicesdataPath, $"分组：{info.Group}\r\n地址：{info.IP}\r\n账号：{info.UserName}\r\n密码：{info.Password}\r\n备注：{info.Desc}\r\n");
                        }
                    }
                    var result = MessageBox.Show($"导出成功，文件路径：{servicesdataPath}。是否需要打开？", "提示", MessageBoxButtons.YesNo);
                    if (result == DialogResult.Yes)
                    {
                        System.Diagnostics.Process.Start("explorer.exe", servicesdataPath);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("导出出错了。" + ex.Message);
            }
        }

        /// <summary>
        /// 导入按钮点击事件，导入服务器信息
        /// </summary>
        private void drtn_Click(object sender, EventArgs e)
        {
            try
            {
                var result = MessageBox.Show("导入前请先阅读导入须知，您是否需要打开导入须知？", "提示", MessageBoxButtons.YesNo);
                if (result == DialogResult.No)
                {
                    daoru();
                }
                else if (result == DialogResult.Yes)
                {
                    // 打开导入须知文档
                    string helpertxtpath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Helper.txt");
                    if (!File.Exists(helpertxtpath))
                    {
                        var helperstr = "导入须知：\r\n";
                        helperstr += "1.导入的文件必须是JSON格式的文件。\r\n";
                        helperstr += "2.导入的文件中必须包含分组、远程主机地址、登录账号、登录密码和备注字段。\r\n";
                        helperstr += "3.导入的文件中备注字段可以为空，但远程主机地址、登录账号、登录密码和分组等字段不能为空，分组可以是等于默认分组。\r\n";
                        helperstr += "4.导入的文件中远程主机地址必须是有效的IP地址或域名。\r\n";
                        helperstr += "5.导入的文件内容格式为：[{\"Desc\":\"远程主机备注1\",\"Group\":\"默认分组\",\"IP\":\"远程主机地址1\",\"Password\":\"密码1\",\"UserName\":\"账号1\"},\r\n{\"Desc\":\"远程主机备注2\",\"Group\":\"默认分组\",\"IP\":\"远程主机地址2\",\"Password\":\"密码2\",\"UserName\":\"账号2\"}]。\r\n";
                        helperstr += "6.如果导入多个，用,分隔。可以使用https://www.json.cn/ 网站进行导入文件内容的编辑。";
                        File.WriteAllText(helpertxtpath, helperstr, Encoding.UTF8);
                    }
                    System.Diagnostics.Process.Start("explorer.exe", helpertxtpath);
                    daoru();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("导入出错了，请检查文件是否存在或格式是否正确。" + ex.Message);
            }
        }

        /// <summary>
        /// 执行导入操作
        /// </summary>
        private void daoru()
        {
            bool isexist = false;
            if (File.Exists(mstscjsonPath))
            {
                isexist = true;
            }
            OpenFileDialog openFileDialog = new OpenFileDialog
            {
                Multiselect = false,
                Filter = "JSON文件|*.json",
                Title = "请选择要导入的JSON文件"
            };
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                string filePath = openFileDialog.FileName;
                if (File.Exists(filePath))
                {
                    string jsonData = File.ReadAllText(filePath);
                    if (!string.IsNullOrEmpty(jsonData))
                    {
                        List<MsctcInfo> importedInfos = JsonHelper.JsonToT<List<MsctcInfo>>(jsonData);
                        if (importedInfos != null && importedInfos.Any())
                        {
                            if (isexist)
                            {
                                initMstscInfos();
                                var importedIPs = importedInfos.Select(m => m.IP).ToList();
                                var ips = mstscInfos.Where(x => importedIPs.Contains(x.IP)).Select(x => x.IP);
                                if (ips.Any())
                                {
                                    foreach (var ip in ips)
                                    {
                                        importedInfos.Remove(importedInfos.FirstOrDefault(x => x.IP == ip));
                                    }
                                }
                                mstscInfos.AddRange(importedInfos);
                                deletejsonAndAdd();
                                shuaxin();
                                MessageBox.Show("导入成功");
                            }
                            else
                            {
                                MessageBox.Show("导入的文件格式不正确或数据为空。");
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show("选择的文件不存在。");
                    }
                }
            }
        }
    }
}

